package com.flow.framework.core.validation.validator;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.exception.ParamCheckedException;
import com.flow.framework.core.validation.annotation.PatternCustomization;
import com.flow.framework.core.validation.validator.base.BaseValidator;

import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;

/**
 * Pattern 校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
public class PatternValidator extends BaseValidator<PatternCustomization, String> {

    private PatternCustomization patternCustomization;

    private java.util.regex.Pattern regexPattern;

    private String errorMsg;

    @Override
    public void initialize(PatternCustomization patternCustomization) {
        this.patternCustomization = patternCustomization;
        try {
            this.regexPattern = java.util.regex.Pattern.compile(patternCustomization.regex(), patternCustomization.flag());
        } catch (Exception e) {
            throw new CheckedException(SystemErrorCode.API_SERVER_ERROR, "regex pattern error.", e);
        }
        this.errorMsg = "value can't match : " + patternCustomization.regex();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (null == value) {
            return true;
        }
        Matcher matcher = regexPattern.matcher(value);
        if (!matcher.matches()) {
            super.logError(context, value, errorMsg);
            throw new ParamCheckedException(patternCustomization.errorCode());
        }
        return true;
    }
}
